﻿Eg.Sys = Eg.Class.extend({
  fps: 30,
  width: 320,
  height: 240,
  realWidth: 320,
  realHeight: 240,
  scale: 1,
  autoStart: true,

  tick: 0,
  smoothPositioning: true,

  clock: null,

  init: function (opts) {
    this.fps = opts.fps;
    this.clock = new Eg.Timer();
    this.canvas = document.getElementById(opts.canvasId);
    this.width = opts.width;
    this.height = opts.height;
    this.autoStart = opts.AutoStart;
    this.scale = opts.scale;
    this.resize(this.width, this.height, this.scale);
    this.context = this.canvas.getContext('2d');
  },
  resize: function (width, height, scale) {
    this.width = width;
    this.height = height;
    this.scale = scale || this.scale;

    this.realWidth = this.width * this.scale;
    this.realHeight = this.height * this.scale;
    this.canvas.width = this.realWidth;
    this.canvas.height = this.realHeight;
  },

  setGame: function (gameClass) {
    if (this.running) {
      this.newGameClass = gameClass;
    }
    else {
      this.setGameNow(gameClass);
    }
  },


  setGameNow: function (gameClass) {
    Eg.game = new (gameClass)();
    Eg.sys.setDelegate(Eg.game);
  },


  setDelegate: function (object) {
    if (typeof (object.run) == 'function') {
      this.delegate = object;
      if (this.autoStart) {
        this.startRunLoop();
      }
    } else {
      throw ('System.setDelegate: No run() function in object');
    }
  },


  stopRunLoop: function () {
    clearInterval(this.intervalId);
    this.running = false;
  },


  startRunLoop: function () {
    this.stopRunLoop();
    this.intervalId = setInterval(this.run.bind(this), 1000 / this.fps);
    this.running = true;
  },

  clear: function (color) {
    this.context.fillStyle = color;
    this.context.fillRect(0, 0, this.realWidth, this.realHeight);
  },
  run: function () {
    Eg.Timer.step();
    this.tick = this.clock.tick();

    this.delegate.run();
    Eg.input.clearPressed();

    if (this.newGameClass) {
      this.setGameNow(this.newGameClass);
      this.newGameClass = null;
    }
  },
  getDrawPos: function (p) {
    return this.smoothPositioning ? Math.round(p * this.scale) : Math.round(p) * this.scale;
  }
});